<template>
  <div class="activity-list-container">
    <!-- 顶部导航栏 - 小红书风格 -->
    <div class="xiaohongshu-navbar">
      <div class="navbar-title">发现</div>
      <div class="navbar-actions">
        <span class="action-icon">🔍</span>
        <span class="action-icon">📷</span>
      </div>
    </div>

    <VirtualWaterfall :items="activities" :columns="2" :estimated-item-height="300" :buffer="5" :column-gap="8" :row-gap="8" class="activities-waterfall" @loadMore="loadMoreActivities">
      <template #item="{ item }">
        <ActivityCard :activity="item" @image-loaded="updateItemHeight" @click="viewActivityDetail(item)" />
      </template>
    </VirtualWaterfall>

    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <span>加载中...</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import VirtualWaterfall from '../components/VirtualWaterfall.vue'
import ActivityCard from '../components/ActivityCard.vue'

const router = useRouter()
const activities = ref([])
const loading = ref(false)
const page = ref(1)
const hasMore = ref(true)

// 优化后的加载活动数据函数
const loadActivities = async (isInitial = false) => {
  if (loading.value || (!isInitial && !hasMore.value)) return

  loading.value = true

  try {
    // 直接获取API数据，不做额外处理
    const response = await fetchActivities(page.value)
    
    // 只在控制台输出一次，减少不必要的日志
    if (isInitial) {
      console.log('Initial data loaded:', response)
    }

    // 直接使用返回的数据，避免额外的循环处理
    if (isInitial) {
      activities.value = response.data
    } else {
      // 使用扩展运算符合并数组，这是一个高效的操作
      activities.value = [...activities.value, ...response.data]
    }

    hasMore.value = response.hasMore
    page.value++
  } catch (error) {
    console.error('Failed to load activities:', error)
  } finally {
    loading.value = false
  }
}

// 加载更多活动
const loadMoreActivities = () => {
  if (!loading.value && hasMore.value) {
    loadActivities()
  }
}

// 后端API应该直接返回格式化好的数据
// 如果后端无法修改，可以在API层做一次性处理
const fetchActivities = async (page) => {
  // 在实际应用中，这里会是真正的API调用
  // const response = await api.get(`/activities?page=${page}`)
  
  // 模拟API调用，返回已经处理好的数据
  await new Promise(resolve => setTimeout(resolve, 800))
  
  // 生成已经处理好的数据，避免在loadActivities中再次处理
  const data = generateProcessedData(page)
  
  return {
    data,
    hasMore: page < 10
  }
}

// 将数据生成逻辑封装到单独的函数中
// 这个函数在实际应用中可能不需要，因为数据会来自后端
const generateProcessedData = (page) => {
  const activityTypes = [
    '派对活动', '展览活动', '讲座活动', '美食活动', '户外活动'
  ]
  
  const descriptions = [
    '超好玩的周末活动，朋友们一起来嗨！🎉',
    '探索艺术的奇妙世界，感受创意的力量✨',
    '这个展览太惊艳了，必须打卡！📸',
    '周末约上闺蜜来这里，绝对不虚此行💕',
    '隐藏在城市角落的文艺小众地，文青必去！📚',
    '超治愈的下午茶，和姐妹们一起来放松心情☕',
    '这个活动也太精彩了吧，错过要再等一年！🔥',
    '偶遇超多有趣的人，社交圈一下子扩大了！👯'
  ]
  
  // 预计算不同活动类型的基础高度
  const typeHeightMap = {
    '派对活动': 120,
    '展览活动': 140,
    '讲座活动': 160,
    '美食活动': 180,
    '户外活动': 200
  }
  
  // 生成10条数据
  return Array.from({ length: 10 }, (_, i) => {
    const typeIndex = Math.floor(Math.random() * activityTypes.length)
    const activityType = activityTypes[typeIndex]
    const baseHeight = typeHeightMap[activityType]
    const imageHeight = baseHeight + Math.floor(Math.random() * 20)
    const descIndex = Math.floor(Math.random() * descriptions.length)
    const contentHeight = 150
    
    return {
      id: `${page}-${i}`,
      title: `${activityType}｜${descriptions[descIndex].substring(0, 10)}...`,
      imageUrl: `https://picsum.photos/400/${imageHeight}?random=${page}-${i}`,
      imageHeight,
      imageCount: `${1}/${Math.floor(Math.random() * 5) + 1}`,
      hasAvatar: Math.random() > 0.2,
      avatarUrl: Math.random() > 0.2 ? `https://i.pravatar.cc/100?u=${page}-${i}` : null,
      date: `${Math.floor(Math.random() * 12) + 1}月${Math.floor(Math.random() * 28) + 1}日`,
      city: ['北京市', '上海市', '广州市', '深圳市'][Math.floor(Math.random() * 4)],
      district: ['朝阳区', '海淀区', '浦东新区', '天河区', '南山区'][Math.floor(Math.random() * 5)],
      description: descriptions[descIndex],
      likes: Math.floor(Math.random() * 200) + 5,
      comments: Math.floor(Math.random() * 30) + 1,
      height: imageHeight + contentHeight
    }
  })
}

// 更新项目高度 - 确保高度计算准确
const updateItemHeight = ({ id, dimensions }) => {
  const index = activities.value.findIndex((item) => item.id === id)
  if (index !== -1) {
    // 获取当前活动
    const activity = activities.value[index]

    // 计算实际内容高度 (图片高度 + 内容区域高度)
    // 内容区域高度包括标题、描述、用户信息等
    const contentHeight = 150 // 固定内容区域高度
    const newHeight = activity.imageHeight + contentHeight

    // 创建新对象以触发响应式更新
    activities.value[index] = {
      ...activity,
      height: newHeight
    }
  }
}

// 查看活动详情
const viewActivityDetail = (activity) => {
  router.push({
    name: 'ActivityDetail',
    params: { id: activity.id }
  })
}

onMounted(() => {
  loadActivities(true)
})
</script>

<style scoped>
.activity-list-container {
  height: 100vh;
  background-color: #f5f5f5; /* 小红书背景色 */
  position: relative;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.xiaohongshu-navbar {
  height: 44px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.navbar-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.navbar-actions {
  display: flex;
  gap: 16px;
}

.action-icon {
  font-size: 18px;
  cursor: pointer;
}

.activities-waterfall {
  flex: 1;
  padding: 8px; /* 增加左右内边距到16px */
  overflow-y: scroll;
  overflow-x: hidden;
  width: 100%;
  box-sizing: border-box;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/* 隐藏滚动条 - Webkit浏览器 */
.activities-waterfall::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
  width: 0;
}

.loading-indicator {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12px 20px;
  color: #666;
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 5;
}

.spinner {
  width: 18px;
  height: 18px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #ff2442; /* 小红书红色 */
  border-radius: 50%;
  margin-right: 8px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>


















